<template>
  <!-- 添加设备 -->
  <div class="page">
    <!-- <div class="top">
			<div style="float:left;"><span @click="goBack" class="goback">设备管理</span>　|　<span>添加网关设备</span></div>
			<el-button type="primary" size="small" id="goback" @click="goBack">返回</el-button>
		</div> -->
    <el-form :model="form" block id="addform" ref="form">
      <el-form-item required label="项目名称:" :label-width="formLabelWidth">
        <el-select v-model="form.product_id" placeholder="选择项目" class="inpu" @change="getDevice(form.product_id)">
          <el-option v-for="item in products" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
        <!-- <el-cascader
					class="inpu"
					v-model="form.product_id"
					:options="products"
					:props="{ checkStrictly:true,expandTrigger:'hover',emitPath:false}">
				</el-cascader> -->
        <br>
        <span class="tip">如果没有选择项，请先添加项目，否则设备无法添加！</span>
        <!-- <el-input v-model="form.name" auto-complete="off" class="inpu" style="transform: translateX(-0.8rem);" placeholder="输入项目名称"></el-input> -->
      </el-form-item>
      <el-form-item label="设备名称:" class="formline" required :label-width="formLabelWidth">
        <el-input v-model="form.equip_name" auto-complete="off" autofocus class="inpu" placeholder="请输入设备名称"
          spellcheck="false"></el-input><br>
        <!-- <span class="tip">名称必须是中，英文字母，数字，下划线或者破折号的组合</span> -->
      </el-form-item>
      <el-form-item label="设备编码:" class="formline" required :label-width="formLabelWidth">
        <el-input v-model="form.equip_code" auto-complete="off" class="inpu" placeholder="请输入设备编码" spellcheck="false"
          @input="toUpper(form.equip_code)"></el-input><br>
        <!-- <span class="tip">编码必须是英文字母，数字，下划线或者破折号的组合</span> -->
      </el-form-item>
      <el-form-item label="版本选择:" class="formline" required :label-width="formLabelWidth">
        <el-select v-model="form.version" placeholder="版本选择" class="inpu" style="width:2.5rem;">
          <el-option v-for="item in versions" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="联网方式:" class="formline" required :label-width="formLabelWidth">
        <el-select v-model="form.network_way" placeholder="联网方式" class="inpu" style="width:2.5rem;">
          <el-option v-for="item in netTypes" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="运行模式:" class="formline" required :label-width="formLabelWidth">
				<el-select v-model="form.run_mode" placeholder="运行模式" class="inpu" @change="changeMode(form.run_mode)" style="width:2.5rem;">
					<el-option v-for="item in runModes" :key="item.value" :label="item.label" :value="item.value">
					</el-option>
				</el-select>
			</el-form-item> -->
      <el-form-item label="应用场景:" class="formline" :label-width="formLabelWidth">
        <el-select v-model="form.app_scene" placeholder="应用场景" :disabled="form.run_mode == 2" class="inpu"
          style="width:2.5rem;">
          <el-option v-for="item in scenes" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="设备图片:" :label-width="formLabelWidth" class="formline2">
        <div class="newimg">
          <img id="new" src="../../static/noimg.png" class="thumb" />
          <input type="file" accept="image/*" id="addid" @change="addUpload" />
          <div class="tip" style="display: block;margin-top:0.2rem;">点击上图可上传（或更换）图片</div>
        </div>
      </el-form-item>
      <!-- <el-form-item class="formline" label="启用状态:" :label-width="formLabelWidth" style="margin-top:-0.4rem;">
        <el-switch style="display:inline-block;vertical-align:top;" v-model="form.equip_state" :width="stateWidth"
          class="demo" active-color="#13ce66" inactive-color="#ccc" active-text="启用" inactive-text="禁用"
          :active-value="one" :inactive-value="zero">
        </el-switch>
      </el-form-item> -->
      <el-form-item label="启用状态:" :label-width="formLabelWidth" class="formline" style="margin-top:-0.3rem;">
        <el-radio-group v-model="form.equip_state">
          <el-radio :label="1" style="font-size:0.3rem;">启用</el-radio>
          <el-radio :label="0" style="font-size:0.3rem;">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="设备排序:" class="formline" :label-width="formLabelWidth">
        <el-input v-model="form.list_order" auto-complete="off" class="inpu" style="width:2.5rem;"
          spellcheck="false"></el-input><br>
        <span class="tip">请输入自然数(0,1,2,3,...),默认以添加的先后顺序排序</span>
      </el-form-item>
      <el-form-item style="margin-left:0.7rem;">
        <el-button type="success" @click="addDevice" size="small">保存</el-button>
        <el-button type="primary" @click="resetForm" size="small">重置</el-button>
      </el-form-item>
    </el-form>
    <el-form :model="mapForm" inline id="r_addform">
      <el-form-item label="设备地址:" :label-width="formLabelWidth">
        <el-input v-model="mapForm.address" placeholder="请输入设备地址" class="inpu" style="width:11.1rem;" spellcheck="false"
          @change="isRepeatAddress(mapForm.address)"></el-input></br>
        <span class="tip2"
          style="margin-top:0.2rem">默认随机定位;建议点击地图获取定位(可缩放或移动地图);如果要手动输入获取,请至少包含"**省**市"的信息(省会或直辖市可至少有"**市");请确保地址和坐标相互匹配!不同设备在同一坐标可能产生遮挡,可通过错位或不一样的名称长度解决。</span>
      </el-form-item><br>
      <el-form-item label="设备坐标:" :label-width="formLabelWidth" class="formline">
        <el-input v-model="mapForm.lng" class="inpu" placeholder="设备地址经度" spellcheck="false"></el-input>
        <el-input v-model="mapForm.lat" class="inpu" placeholder="设备地址纬度" spellcheck="false"></el-input>
        <el-button size="small" type="primary" style="margin-left:0.4rem;" @click="getPoint">获取坐标</el-button>
        <!-- 地图控件 -->
        <div id="addMap" ref="addMap"></div>
        <!-- <button class="mapbtn" @click="FullScreen">全屏地图</button> -->
        <!-- <span>提示:点击地图空白处可进入全屏模式，按“esc”键退出全屏！</span> -->
        <!-- 地图结束 -->
      </el-form-item>
    </el-form>

  </div>
</template>

<script>
export default {
  name: 'addDevice',
  data() {
    return {
      products: [],
      one: 1,
      zero: 0,
      value: '',
      formLabelWidth2: '80px',
      formLabelWidth: '110px',
      stateWidth: 66,
      baseurl: this.$baseurl,
      icon: "https://gou-bin.oss-cn-beijing.aliyuncs.com/yunken/local.png",
      furl: '',
      ws: '',
      bgurl: '',
      upshow: true,
      map: null,
      marker: null,
      city: '西安市',
      myIcon: null,
      form: {
        product_id: '',
        // slave_type:1,
        list_order: 50,
        network_way: 1,
        app_scene: 1,
        equip_name: '',
        equip_code: '',
        type: 1,
        //run_mode:1,
        version: 4,
        equip_state: 1
      },
      netTypes: [{
        value: 1,
        label: '4G'
      }, {
        value: 2,
        label: 'Wifi'
      }, {
        value: 3,
        label: '网口'
      },],
      versions: [{
        value: 3,
        label: 'YK5.3'
      },
      {
        value: 4,
        label: 'YK5.4'
      },
      ],
      runModes: [{
        value: 1,
        label: '边缘采集'
      },
      {
        value: 2,
        label: '数据透传'
      }
      ],
      scenes: [{
        value: 1,
        label: '通用'
      },
      {
        value: 2,
        label: '水利'
      },
      {
        value: 5,
        label: 'MQTT遥测'
      }
        // {
        //    value:3,
        //    label:'私有协议-A'
        // }
      ],
      options: [],
      addresses: [],
      point: {
        lat: 34.340801,
        lng: 108.940734
      },
      // moulds: [
      // 	{
      // 		value: 0,
      // 		label: '不选择'
      // 	}
      // ],
      // mapForm: {
      //     address: '陕西省西安市未央区张家堡街道凤城八路147号风景御园',
      //     lat: 34.340801,
      //     lng: 108.940734
      // },
      mapForm: {
        address: '',
        lat: '',
        lng: ''
      }
    }
  },
  created() {
    var randnum1 = Number((Math.random() * 0.1).toFixed(6));
    var randnum2 = Number((Math.random() * 0.1).toFixed(6));
    this.point.lat = 34.340801 + randnum1;
    this.point.lng = 108.940734 + randnum2;
    this.getProduct();
  },

  mounted() {
    this.mapForm.lat = this.point.lat;
    this.mapForm.lng = this.point.lng;
    this.showMap("addMap");
  },
  methods: {
    getProduct() {
      var that = this;
      this.$http({
        method: 'post',
        url: '/api/product/tree',
        data: {}
      }).then(res => {
        if (res && res.data.result == "success") {
          this.products = res.data.data;
          this.form.product_id = res.data.data[0].value;
        }
        //console.log("charu")
      }).catch(error => {

        console.log(error);
      });
    },

    goBack() {
      this.$router.go(-1);
    },

    changeMode(mode) {
      if (mode == 2) {
        this.form.app_scene = 1;
      }
    },

    toUpper(code) {
      this.form.equip_code = code.toUpperCase();
    },

    isRepeatAddress(address) {
      //console.log(address);
      if (!this.addresses.length || !address) {
        return false
      };
      for (let i = 0, len = this.addresses.length; i < len; i++) {
        if (this.addresses[i].label == address) {
          this.$message({
            type: 'info',
            dangerouslyUseHTMLString: true,
            message: '<p>提示：当前地址与原有设备<span style="color:red">' + this.addresses[i].value +
              '</span>的地址完全重复，在设备地图上会形成遮挡，</br>建议你可以通过地址轻微错位或修改设备名称长度来解决，也可以忽略不处理！</p>',
            center: true,
            showClose: true,
            duration: 10000,
            offset: 300
          })
          break;
        }
      }
    },

    addUpload() {
      this.ws = null;
      var that = this;
      var fileLen = document.getElementById('addid').files;
      this.ws = fileLen[0];
      var reads = new FileReader();
      reads.readAsDataURL(this.ws);
      reads.onload = function (e) {
        document.getElementById('new').src = this.result;
      }
    },
    addDevice() {
      var that = this;
      var upform = new FormData();
      for (var key in this.form) {
        upform.append(key, that.form[key]);
      }
      upform.append("image", that.ws);
      //upform.append("slave_type", that.form.slave_type);
      upform.append("geo_coord", JSON.stringify([that.mapForm.lng, that.mapForm.lat]));
      upform.append("geo_name", that.mapForm.address);
      //upform.append("template_id", that.form.template_id);
      this.$http({
        method: 'post',
        url: 'api/equip/add',
        data: upform
      }).then(res => {
        if (res && res.data.result == "success") {
          this.$message({
            message: '恭喜,添加设备成功!',
            type: 'success',
            center: true
          });
          this.$router.go(-1);
        }
      }).catch(error => {
        console.log(error);

      });
    },
    resetForm() {
      this.form = {
        product_id: '',
        // slave_type:1,
        list_order: 50,
        network_way: 1,
        app_scene: 1,
        equip_name: '',
        equip_code: '',
        type: 1,
        //run_mode:1,
        version: 2,
        equip_state: 1
      };
      this.form.product_id = this.products[0].value;
      this.showMap("addMap");
    },

    getPoint() {
      var that = this;
      if (this.mapForm.address) {
        this.mapForm.lng = '';
        this.mapForm.lat = '';
        var markers = [];
        if (that.marker) {
          markers.push(that.marker);
        }
        that.map.remove(markers);
        that.map.plugin('AMap.Geocoder', function () {
          var geocoder = new AMap.Geocoder({
            city: "全国",
          }); //城市设为北京，默认：“全国”
          geocoder.getLocation(that.mapForm.address, function (status, result) {
            if (status === 'complete' && result.geocodes.length) {
              var lnglat = result.geocodes[0].location;
              //console.log(lnglat);
              //document.getElementById('lnglat').value = lnglat;
              that.mapForm.lng = lnglat.lng;
              that.mapForm.lat = lnglat.lat;
              that.marker = new AMap.Marker({
                icon: that.icon,
                position: [that.mapForm.lng, that.mapForm.lat],
                offset: new AMap.Pixel(-16, -16)
              });
              //that.marker.setPosition(lnglat);
              that.map.add(that.marker);
              that.map.setFitView(that.marker);
            } else {
              that.$message({
                message: '当前的输入地址无法获取坐标，你可以重新输入或点击地图获取!',
                type: 'error',
                center: true
              });
            }
          });
        });

      } else {
        this.$message({
          message: '地址不能为空，请输入!',
          type: 'error',
          center: true
        });
      }
    },

    // onComplete(res) {
    //     //console.log(res);
    // },
    // onError(error) {
    //     //console.log(error);
    // },
    showMap(idstr) {
      var that = this;
      that.map = new AMap.Map(idstr);
      //that.map.plugin('AMap.Geolocation', function() {
      // var geolocation = new AMap.Geolocation({
      //     enableHighAccuracy: true, //是否使用高精度定位，默认:true
      //     timeout: 10000, //超过10秒后停止定位，默认：无穷大
      //     maximumAge: 0, //定位结果缓存0毫秒，默认：0
      //     convert: true, //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
      //     showButton: false, //显示定位按钮，默认：true
      //     //buttonPosition: 'LB',    //定位按钮停靠位置，默认：'LB'，左下角
      //     //buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
      //     //showMarker: true,        //定位成功后在定位到的位置显示点标记，默认：true
      //     //showCircle: true,        //定位成功后用圆圈表示定位精度范围，默认：true
      //     panToLocation: true, //定位成功后将定位到的位置作为地图中心点，默认：true
      //     zoomToAccuracy: true //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
      // });
      AMap.plugin([
        'AMap.ToolBar',
        'AMap.Scale'
      ], function () {
        // 在图面添加工具条控件，工具条控件集成了缩放、平移、定位等功能按钮在内的组合控件
        that.map.addControl(new AMap.ToolBar());

        // 在图面添加比例尺控件，展示地图在当前层级和纬度下的比例尺
        that.map.addControl(new AMap.Scale());
        // 在图面添加鹰眼控件，在地图右下角显示地图的缩略图
        //that.map.addControl(new AMap.OverView({isOpen:true}));
        // 在图面添加类别切换控件，实现默认图层与卫星图、实施交通图层之间切换的控制
        //that.map.addControl(new AMap.MapType());
        // 在图面添加定位控件，用来获取和展示用户主机所在的经纬度位置
        // that.map.addControl(new AMap.Geolocation());
      });
      //that.map.addControl(geolocation);
      //标注默认随机坐标；
      that.marker = new AMap.Marker({
        icon: that.icon,
        position: [that.point.lng, that.point.lat],
        offset: new AMap.Pixel(-16, -16)
      });
      that.marker.setMap(that.map);
      //根据默认随机坐标获取地址；
      AMap.service('AMap.Geocoder', function () { // 回调函数
        var geocoder = new AMap.Geocoder({
          radius: 2000, //逆地理编码时，以给定坐标为中心点半径范围，单位：米，取值0-3000，默认1000
          extensions: "all" //base，返回基本地址信息，all，返回所有地址信息
        });
        geocoder.getAddress([that.point.lng, that.point.lat], function (status, result) {
          if (status === 'complete' && result.info === 'OK') {
            // console.log(result.regeocode.formattedAddress);
            //console.log(result);
            that.mapForm.address = result.regeocode.formattedAddress;
          } else {
            that.mapForm.address = "获取地理位置失败"
          }
        });
      });
      //默认标注结束
      //高德地图随机定多点(参考写法)；
      //var center = new AMap.LngLat(114.21694,22.72045);
      // 	  for (var j = 0; j <3; j++) {
      // 		  var lnglat = new AMap.LngLat(center.getLng() + Math.random()*0.1, center.getLat() +  Math.random()*0.1);
      // 		  var marker = new AMap.Marker({
      //			   position: lnglat,
      // 			   raiseOnDrag:true,
      // 			   opacity:1,
      // 				icon:'http://webapi.amap.com/theme/v1.2/0.png'

      // 			  });
      // 	       marker.setMap(map);
      //        }
      //随机多点结束
      that.map.setZoomAndCenter(5, [that.point.lng, that.point.lat]);
      //geolocation.getCurrentPosition();
      //AMap.event.addListener(geolocation, 'complete', that.onComplete); //返回定位信息
      // AMap.event.addListener(geolocation, 'error', that.onError); //返回定位出错信息
      that.map.on('click', function (e) {
        var markers = [];
        if (that.marker) {
          markers.push(that.marker);
        }
        that.map.remove(markers);
        that.point.lng = e.lnglat.lng;
        that.point.lat = e.lnglat.lat;
        that.mapForm.lng = e.lnglat.lng;
        that.mapForm.lat = e.lnglat.lat;

        that.marker = new AMap.Marker({
          icon: that.icon,
          position: [that.point.lng, that.point.lat],
          offset: new AMap.Pixel(-16, -16)
        });
        that.marker.setMap(that.map);

        AMap.service('AMap.Geocoder', function () { // 回调函数
          var geocoder = new AMap.Geocoder({
            radius: 2000, //逆地理编码时，以给定坐标为中心点半径范围，单位：米，取值0-3000，默认1000
            extensions: "all" //base，返回基本地址信息，all，返回所有地址信息
          });
          geocoder.getAddress([that.point.lng, that.point.lat], function (status, result) {
            if (status === 'complete' && result.info === 'OK') {
              // console.log(result.regeocode.formattedAddress);
              //console.log(result);
              that.mapForm.address = result.regeocode.formattedAddress;
              that.isRepeatAddress(that.mapForm.address);
            } else {
              that.mapForm.address = "获取地理位置失败"
            }
          });
        });
      });
      //});
    }

  }
}
</script>

<style scoped>
@media all and (max-width:1600px) {
  .formline {
    margin-top: -0.4rem !important;
  }
}

.inpu /deep/ .el-input__inner {
  padding-left: 4px;
}

#addform {
  position: relative;
  float: left;
  text-align: left;
  margin-top: 0.3rem;
  width: 34%;
  /* height: 12.4rem; */
  /* border:1px solid red; */
  line-height: 0.6rem;
  z-index: 10;
}

#r_addform {
  position: relative;
  line-height: 0.6rem;
  float: left;
  margin-top: 0.3rem;
  text-align: left;
  width: 65%;
  z-index: 10;
  /* border:1px solid red; */
}

.upimg {
  width: 2rem;
  height: 1.2rem;
}

.inpu {
  width: 5.5rem;
}

.tip,
.tip2 {
  display: inline-block;
  color: #FF5722;
  font-size: 0.25rem;
  line-height: 0.35rem;
  transform: translateY(-0.1rem);
}

#addMap {
  margin-top: 0.2rem;
  width: 16rem;
  height: 10rem;
  border: 1px solid #ccc;
}

#upload {
  position: relative;
  left: -1.4rem;
  top: -0.3rem;
  z-index: 11;
}

#addid {
  width: 1.5rem;
  height: 1.5rem;
  /* border:1px solid red; */
  overflow: hidden;
  position: absolute;
  left: 0;
  top: 0;
  z-index: 12;
  opacity: 0;
}

.thumb {
  width: 1.5rem;
  height: 1.5rem;
}

.formline {
  /* border:1px solid red; */
  width: 100%;
  margin-top: -0.3rem;
}

.formline2 {
  width: 100%;
  margin-top: -0.2rem;
}

.tip2 {
  width: 16rem;
}
</style>
